<?php
namespace App\Http\Admin\Product\Controllers;

use App\Eloquent\Ygt\ProductFields;
use Framework\BaseClass\Http\Admin\Controller;
use App\Eloquent\Ygt\Product as ProductModel;
use \App\Eloquent\Ygt\Qrcode;
use Excel;




class SnCodeController extends Controller
{
    protected $company = false;

    public function __construct()
    {
        parent::__construct();
    }

    protected $rules = [
        'number' => 'bail|required|integer',
        'total_number' => 'required|integer',
    ];

    public function add(){
        $param = request()->all();
        if (request()->isMethod('post')) {
            $result = $this->validateRequestParameters($param, $this->rules, false);

            if ($result) {
                return $this->ajaxFail($result);
            }

            //添加
            //生成数据
            $lists = [];

            for($i=0;$i<$param['number'];$i++){
                $temp = [
                    'sn'=>'',
                    'total_number'=>$param['total_number'],
                    'preinstall_bind_product_id'=>$param['product_id']
                ];

                $productNo          = mt_rand(10000000,99999999);
                $temp['sn']           = \App\Eloquent\Ygt\Qrcode::getSn($productNo);

                $temp['id'] = Qrcode::insertOneData( $temp, 'id' );
                $lists[] = $temp;
            }

            //导出
            if($param['act'] == 'sign_out'){
                if($param['product_id']){
                    //有商品先找出商品的规格信息
                    $sign_out_arr[] = [
                        'no_lbl','no_value','code',
                        'key1_lbl','key1_value','key2_lbl','key2_value',
                        'key3_lbl','key3_value','key4_lbl','key4_value',
                        'key5_lbl','key5_value','key6_lbl','key6_value',
                    ];
                    $fields_list = ProductFields::where('product_id','=',$param['product_id'])
                        ->get(['field_name','varchar'])->toArray();

                    $fields_arr = [];
                    foreach($fields_list as $key=>$v){
                        $fields_arr[] = $v['field_name'];
                        $fields_arr[] = $v['varchar'];
                        if(count($fields_arr)>=8){
                            break;
                        }
                    }
                    //确保4组 8个
                    for($i=count($fields_arr);$i<=8;$i++){
                        $fields_arr[] = '';
                    }

                    //获得供应商和堆位信息 seller_company_id, place_name
                    $productInfo = ProductModel::where('ygt_product.id','=',$param['product_id'])
                        ->leftJoin('ygt_seller_company','ygt_seller_company.id','=','ygt_product.seller_company_id')
                        ->get(
                            [
                                'ygt_seller_company.title',
                                'ygt_product.place_name'
                            ]
                        )
                        ->toArray();

                    if($productInfo){
                        $productInfo = $productInfo[0];
                        $fields_arr[] = $productInfo['title'];
                        $fields_arr[] = $productInfo['place_name'];
                    }
                    else{
                        $fields_arr[] = '';
                        $fields_arr[] = '';
                    }


                    foreach($lists as $key=>$v){
                        $t_arr = ['编号',$v['sn'],$v['sn']];
                        $sign_out_arr[] = array_merge($t_arr,$fields_arr);
                    }
                }
                else{
                    $sign_out_arr[] = ['code_1','code_2'];

                    $len = count($lists);
                    for($i=0;$i<$len;){
                        $sign_out_arr[] = [
                            $lists[$i++]['sn'],
                            isset($lists[$i])?$lists[$i]['sn']:''
                        ];
                        $i++;
                    }
                }

                //调用导出
                return $this->exportExcel(['data'=>$sign_out_arr]);
            }
            else{
                return $this->ajaxSuccess();
            }
        }
        else{
            return $this->view('add');
        }
    }

    public function exportExcel($data)
    {
        $exportData     = isset($data['data']) ? $data['data'] : [];
        $cellData       = isset($data['cell']) ? $data['cell'] : [];
        \Excel::create('码列表', function($excel) use($exportData,$cellData) {
            $excel->sheet('Sheetname', function($sheet) use($exportData,$cellData) {
                $sheet->freezeFirstRow();
                $sheet->setAutoSize(true);
                $sheet->fromArray($exportData, null, 'A1', false, false);
                foreach($cellData as $val)
                {
                    $sheet->mergeCells($val);
                    $sheet->cells($val, function($cells) {
                        $cells->setAlignment('center');
                        $cells->setValignment('center');
                    });
                }
            });
        })->export('xls');

    }

    public function edit(){
        $admin_user         = request()->user('admin')->toArray();
        $company_id         = $admin_user['company_id'];

        $params             = $this->requestJson();
        $id                 = isset($params['id']) ? $params['id'] : 0;
        $total_number       = $params['total_number'];
        $productNo          = mt_rand(10000000,99999999);
        $qrcodeSn           = \App\Eloquent\Ygt\Qrcode::getSn($productNo);

        $data               = [
            'sn'=>$qrcodeSn,
            'total_number'=>$total_number,
        ];

        if( $id ){
            $where          = ['id'=>$id];
            $result         = Qrcode::updateOneData( $where, $data );
        } else {
            $result         = Qrcode::insertOneData( $data, 'id' );
        }
        if( $result ){
            return $this->ajaxSuccess( '成功' );
        } else {
            return $this->ajaxFail( '失败' );
        }
    }

    public function delete()
    {
        $admin_user         = request()->user('admin')->toArray();
        $company_id         = $admin_user['company_id'];

        $id                 = request('id',0);
        if($id){
            $where          = ['id'=>$id];
            $del_result     = Qrcode::del($where);
            if( $del_result !== false ){
                return $this->ajaxFail('成功');
            }
            else{
                return $this->ajaxFail('失败');
            }
        } else {
            return $this->ajaxFail('失败');
        }
    }

    public function selectProductAjax(){
        $adminUser         = request()->user('admin')->toArray();
        $companyId         = $adminUser['company_id'];

        $id = request('id',0);
        $product_id           = request('product_id',0);

        $where              = ['id'=>$id];
        $data               = ['product_id'=>$product_id];
        $result             = Qrcode::updateOneData($where,$data);
        if( $result ){
            return $this->ajaxSuccess('成功');
        } else {
            return $this->ajaxFail('失败');
        }
    }

    public function productLists(){
        $adminUser         = request()->user('admin')->toArray();
        $companyId         = $adminUser['company_id'];

        if (request()->isMethod('post')) {
            $keyword          = request('keyword');

            $obj = new ProductModel();
            if(!empty($keyword)){
                $obj = $obj->where('product','like','%'.$keyword.'%');
            }

            $list = $obj->get();
            return ['list'=>$list,'pageSize'=>10000];
        }
        else{
            $product_id           = request('product_id',0);
            $id = request('id',0);

            //获得材料列表
            $list = ProductModel::get()->toArray();
            $data = ['id'=>$id,'product_id'=>$product_id,'list'=>$list];
        }

        return $this->view('product-list-for-select',$data);
    }

    public function lists(){
        $adminUser         = request()->user('admin')->toArray();
        $companyId         = $adminUser['company_id'];

        if (request()->isMethod('post')) {
            $sn         = request( 'sn', '' );
            $type         = request( 'type', 0 );

            $obj = new Qrcode();
            if(!empty($sn)){
                $obj = $obj->where("ygt_qrcode.sn",'=',$sn);
            }

            if($type == 1){
                $obj = $obj->where("ygt_qrcode.product_id",'!=',0);
            }
            else if($type == 2){
                $obj = $obj->where("ygt_qrcode.product_id",'=',0);
            }

            $fileds = [
                'ygt_qrcode.id',
                'ygt_qrcode.sn',
                'ygt_qrcode.product_id',
                'ygt_qrcode.total_number',
                'ygt_qrcode.now_number',
                'ygt_product.product_name'
            ];

            $lists = $obj->leftJoin('ygt_product','ygt_qrcode.product_id','=','ygt_product.id')
                ->orderBy('id','desc')
                ->get($fileds)->toArray();
            $result         = collect($lists)->toJson();
            return $result;
        } else {

            $toolbarItem       = 'export';
            if( $companyId == 1 )
            {
                $toolbarItem   .= ',add';
            }

            $obj = new Qrcode();

            $fileds = [
                'ygt_qrcode.id',
                'ygt_qrcode.sn',
                'ygt_qrcode.product_id',
                'ygt_qrcode.total_number',
                'ygt_qrcode.now_number',
                'ygt_product.product_name'
            ];

            $obj->leftJoin('ygt_product','ygt_qrcode.product_id','=','ygt_product.id')
                ->orderBy('id','desc')
                ->get($fileds)->toArray();


            return $this->view('lists', compact('toolbarItem') );
        }
    }

}